package me.zk;

import java.util.Arrays;

/**
 * 快速排序，双端循环
 * @Author: zhang kai
 * @Date: 2022/06/27
 * @Description:
 */
public class QuickSortDemo1 {


    public static void quickSort(int[] array, int startIndex, int endIndex) {
        //递归结束条件 startIndex >= endIndex
        if (startIndex >= endIndex) {
            return;
        }
        //得到基准元素的位置
        int pivotIndex = partition(array,startIndex, endIndex);
        quickSort(array, startIndex,pivotIndex-1);
        quickSort(array, pivotIndex+1, endIndex);
    }

    private static int partition(int[] arr, int startIndex, int endIndex) {
        //取第一个位置
        int pivot = arr[startIndex];
        int left = startIndex;
        int right = endIndex;
        while (left != right) {
            //控制right指针比较并左移
            while (left < right && arr[right] > pivot) {
                right--;
            }
            //控制left指针比较并右移
            while (left < right && arr[left] <= pivot) {
                left++;
            }
            //交换元素
            if (left < right) {
                int tmp = arr[left];
                arr[left] = arr[right];
                arr[right] = tmp;
            }
        }
        //pivot和指针重合点交换
        arr[startIndex] = arr[left];
        arr[left] = pivot;
        return left;
    }

    public static void main(String[] args) {
        int[] array = {4,4,6,5,3,2,8,1,0,12};
        quickSort(array,0, array.length-1);
        System.out.println(Arrays.toString(array));
    }
}
